﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FloodFree.Common;

namespace FloodFree.Web.Areas.Api.Controllers
{
    public class CitiesController : BaseController
    {
        //
        // GET: /Api/Cities/

        public JsonResult Index()
        {
            var cities = (from x in db.Cities.Include("States")
                          select new
                          {
                              Id = x.Id,
                              Name = x.Name,
                              State = x.State.Name
                              
                          }).ToList();
            return Json(new { Cities = cities }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Api/Cities/Details/5

        public JsonResult Details(int id)
        {
            var sensors = (from s in db.Sensors
                           where(s.City.Id.Equals(id))
                           select new { SensorUUID = s.SensorUUID,
                           Latitude = s.Latitude,
                           Longitude = s.Longitude,
                           Address = s.Address,
                           LastStatus = (from u in s.Updates
                                        where u.StatusType.Equals(1)
                                         orderby u.Date descending 
                                        select u.Status).FirstOrDefault(),
                           LastStatusDate = (from u in s.Updates
                                                 where u.StatusType.Equals(1)
                                                 orderby u.Date descending
                                             select u.Date).FirstOrDefault()
                           
                           }).ToList();



            var sensorsTmp = (from s in sensors
                              select new
                              {
                                  SensorUUID = s.SensorUUID,
                                  Latitude = s.Latitude,
                                  Longitude = s.Longitude,
                                  Address = s.Address,
                                  LastStatus = s.LastStatus,
                                  LastStatusDate = s.LastStatusDate.ToString("dd/MM/yyyy hh:mm")
                              }).ToList();

            return Json(new { Sensors = sensorsTmp }, JsonRequestBehavior.AllowGet);
        }
    }
}
